package gui;


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

import menus.CustMenu;
import menus.DriverMenu;
import menus.ManagerMenu;
import menus.PosMenu;
import menus.AlbumMenu;

/*
 * MvbView allows a user to view and manipulate the branch table.
 * Additional functionality may be added in the future, such as
 * viewing and manipulating the driver, license, and exam tables.
 */
public class MainView extends JFrame {
	// initial position of the main frame
	private int framePositionX;
	private int framePositionY;

	// initial size of main frame
	private Rectangle frameBounds = null;

	// the status text area for displaying error messages
	private JTextArea statusField = new JTextArea(5, 0);

	// the scrollpane that will hold the table of database data
	JScrollPane tableScrPane = new JScrollPane();
	
	// used to start/continue purchases and returns
	private int lastRec = -1;

	public ImageIcon georgeIcon = createImageIcon("images/george.png");
	public ImageIcon normIcon = createImageIcon("images/norm.png");
	public ImageIcon starIcon = createImageIcon("images/star.gif");
	
	private ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = this.getClass().getResource(path); // images must be in gui.images
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }
	////////////////////////////////////////////// Add menus here
	
	private JMenu managerMenu;
	private JMenu albumMenu;
	private JMenu songAdmin;
	private JMenu posMenu;
	private JMenu custMenu;
	private JPanel panel;
	private JButton btnNewButton;

	/////////////////////////////////////// I think this determines order of menu items
	private void setupMenus(JMenuBar menuBar) {
		setupManagerMenu(menuBar);
		setupAlbumAdminMenu(menuBar);
		setupPosMenu(menuBar);
		setupCustMenu(menuBar);
		
		// Setup some other menus. You may be asked to add functionality
		// to these menus in an assignment.
		// JMenu menu = new JMenu("Driver Admin");
		// menu.setMnemonic(KeyEvent.VK_D);
		// menuBar.add(menu);
		// menu = new JMenu("License Admin");
		// menu.setMnemonic(KeyEvent.VK_L);
		// menuBar.add(menu);
		// menu = new JMenu("Exam Admin");
		// menu.setMnemonic(KeyEvent.VK_E);
		// menuBar.add(menu);
	}

	
	/*
	 * Adds menu items to the Branch Admin menu and then adds the menu to the
	 * menubar
	 */
	private void setupManagerMenu(JMenuBar mb) {
		managerMenu = new JMenu("Manager");

		// when alt-b is pressed on the keyboard, the menu will appear
		managerMenu.setMnemonic(KeyEvent.VK_I);

		// JMenuItem menuItem = createMenuItem(branchAdmin, "Show All Items",
		// KeyEvent.VK_I, "Show Items");
		// // setup a short cut key for this menu item
		// menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I,
		// ActionEvent.CTRL_MASK));

		JMenuItem menuItem = createMenuItem(managerMenu, "Edit All Items",
				KeyEvent.VK_E, "Edit Items");
		menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E,
				ActionEvent.CTRL_MASK));

		createMenuItem(managerMenu, "Add New Item...", KeyEvent.VK_I, "Add Item");

		createMenuItem(managerMenu, "Update Price/Stock...", KeyEvent.VK_U,
				"Update Stock");

		createMenuItem(managerMenu, "Set Delivered Date...", KeyEvent.VK_D,
				"Set Delivered");

		createMenuItem(managerMenu, "Daily Sales Report...", KeyEvent.VK_D,
				"Sales Report");

		createMenuItem(managerMenu, "Best Sellers...", KeyEvent.VK_D,
				"Best Sellers");

		mb.add(managerMenu);
	}



	private void setupAlbumAdminMenu(JMenuBar mb) {
		albumMenu = new JMenu("Album Admin");
		albumMenu.setMnemonic(KeyEvent.VK_S);
		
		createMenuItem(albumMenu, "Show Albums & Singers", KeyEvent.VK_S, "Show Singers");
		createMenuItem(albumMenu, "Add Singer...", KeyEvent.VK_A, "Add Singer");
		
		//JMenuItem menuItem = 
		createMenuItem(albumMenu, "Edit Singers", KeyEvent.VK_E, "Edit Singers");
		//menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, ActionEvent.CTRL_MASK));
		
		createMenuItem(albumMenu, "Show Albums & Songs", KeyEvent.VK_S, "Show Songs");
		
		createMenuItem(albumMenu, "Add Song...", KeyEvent.VK_A, "Add Song");
		
		//JMenuItem menuItem = 
		createMenuItem(albumMenu, "Edit Songs", KeyEvent.VK_E, "Edit Songs");
		//menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, ActionEvent.CTRL_MASK));
		
		mb.add(albumMenu);
	}

	private void setupPosMenu(JMenuBar mb) {
		
		posMenu = new JMenu("POS");
		posMenu.setMnemonic(KeyEvent.VK_P);
		
		createMenuItem(posMenu, "New Purchase...", KeyEvent.VK_T,
				"np");
		createMenuItem(posMenu, "Continue Purchase...", KeyEvent.VK_T,
				"cp");
		createMenuItem(posMenu, "Finish Purchase...", KeyEvent.VK_T,
				"fp");
		createMenuItem(posMenu, "New Return...", KeyEvent.VK_T,
				"nr");
		createMenuItem(posMenu, "Continue Return...", KeyEvent.VK_T,
				"cr");
		createMenuItem(posMenu, "Finish Return...", KeyEvent.VK_T,
				"fr");
		
// code for hotkey:
//		JMenuItem menuItem = createMenuItem(posMenu, "Edit Songs",
//				KeyEvent.VK_S, "Edit Songs");
//		menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D,
//				ActionEvent.CTRL_MASK));
//		
		mb.add(posMenu);
	}
		
		private void setupCustMenu(JMenuBar mb) {
			
			custMenu = new JMenu("Customer");
			custMenu.setMnemonic(KeyEvent.VK_P);
			
			createMenuItem(custMenu, "Register...", KeyEvent.VK_T,
					"reg");
			createMenuItem(custMenu, "Login...", KeyEvent.VK_T,
					"log");
			createMenuItem(custMenu, "Search Item...", KeyEvent.VK_T,
					"search");
			createMenuItem(custMenu, "Add to basket...", KeyEvent.VK_T,
					"add");
			createMenuItem(custMenu, "Checkout...", KeyEvent.VK_T,
					"chkout");
	
			mb.add(custMenu);
	}
	
	/*
	 * This method registers the controllers for all items in each menu. This
	 * method should only be executed once.
	 */
	public void registerControllers() {
		JMenuItem menuItem;

		// BranchController handles events on the branch admin menu items (i.e. when they are clicked)
		
		ManagerMenu bc = new ManagerMenu(this);
		for (int i = 0; i < managerMenu.getItemCount(); i++) {
			menuItem = managerMenu.getItem(i);
			menuItem.addActionListener(bc);
		}

		AlbumMenu ac = new AlbumMenu(this);
		for (int i = 0; i < albumMenu.getItemCount(); i++) {
			menuItem = albumMenu.getItem(i);
			menuItem.addActionListener(ac);
		}

		PosMenu pc = new PosMenu(this);
		for (int i = 0; i < posMenu.getItemCount(); i++) {
			menuItem = posMenu.getItem(i);
			menuItem.addActionListener(pc);
		}

		CustMenu mc = new CustMenu(this);
		for (int i = 0; i < custMenu.getItemCount(); i++) {
			menuItem = custMenu.getItem(i);
			menuItem.addActionListener(mc);
		}
		
	}
	
	
	/////////////////////////////////////  code below doesn't change when menus are changed //////////////////////////////////
	
	/*
	 * Default constructor. Constructs the main window.
	 */
	public MainView() {
		// should call the constructor of the superclass first
		super("Three Oh Fo' Music Sto'");
		setSize(700, 501);

		// the content pane;
		// components will be spaced vertically 10 pixels apart
		JPanel contentPane = new JPanel(new BorderLayout(0, 10));
		setContentPane(contentPane);

		// leave some space around the content pane
		contentPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

		// setup the menubar
		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);

		// indent first menu
		menuBar.add(Box.createRigidArea(new Dimension(10, 0)));

		setupMenus(menuBar);

		// the scrollpane for the status text field
		JScrollPane statusScrPane = new JScrollPane(statusField);
		statusScrPane
				.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		statusScrPane.setBorder(BorderFactory.createLoweredBevelBorder());

		// set status field properties
		statusField.setEditable(false);
		statusField.setLineWrap(true);
		statusField.setWrapStyleWord(true);

		// add the panes to the content pane
		contentPane.add(tableScrPane, BorderLayout.CENTER);
		contentPane.add(statusScrPane, BorderLayout.NORTH);
		{
			panel = new JPanel();
			contentPane.add(panel, BorderLayout.SOUTH);
			{
				btnNewButton = new JButton("New button");
				
				panel.add(btnNewButton);
			}
		}

		// center the main window
		Dimension screenSize = getToolkit().getScreenSize();
		frameBounds = getBounds();
		framePositionX = (screenSize.width - frameBounds.width) / 2;
		framePositionY = (screenSize.height - frameBounds.height) / 2;
		setLocation(framePositionX, framePositionY);

		// anonymous inner class to terminate program
		addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
	}
	
	/*
	 * Creates a menu item and adds it to the given menu. If the menu item has
	 * no mnemonic, set mnemonicKey to a negative integer. If it has no action
	 * command, set actionCommand to the empty string "". By setting the menu
	 * item's action command, the event handler can determine which menu item
	 * was selected by the user. This method returns the menu item.
	 */
	private JMenuItem createMenuItem(JMenu menu, String label, int mnemonicKey,
			String actionCommand) {
		JMenuItem menuItem = new JMenuItem(label);

		if (mnemonicKey > 0) {
			menuItem.setMnemonic(mnemonicKey);
		}

		if (actionCommand.length() > 0) {
			menuItem.setActionCommand(actionCommand);
		}

		menu.add(menuItem);

		return menuItem;
	}

	/*
	 * Places the given window approximately at the center of the screen
	 */
	public void centerWindow(Window w) {
		Rectangle winBounds = w.getBounds();
		w.setLocation(framePositionX + (frameBounds.width - winBounds.width)
				/ 2, framePositionY + (frameBounds.height - winBounds.height)
				/ 2);
	}

	/*
	 * This method adds the given string to the status text area
	 */
	public void updateStatusBar(String s) {
		// trim() removes whitespace and control characters at both ends of the
		// string
		statusField.append(s.trim() + "\n");

		// This informs the scroll pane to update itself and its scroll bars.
		// The scroll pane does not always automatically scroll to the message
		// that was
		// just added to the text area. This line guarantees that it does.
		statusField.revalidate(); // doesn't work?
		statusField.setCaretPosition(statusField.getDocument().getLength());
	}

	/*
	 * This method adds the given JTable into tableScrPane
	 */
	public void addTable(JTable data) {
		tableScrPane.setViewportView(data);
	}


	public static void main(String[] args) {
		MainView mainFrame = new MainView();

		// we will not call pack() on the main frame
		// because the size set by setSize() will be ignored
		mainFrame.setVisible(true);

		// create the login window
		// this will now use auto-login and create connection
		LoginWindow lw = new LoginWindow(mainFrame);

		lw.addWindowListener(new ControllerRegister(mainFrame));

		// pack() has to be called before centerWindow()
		// and setVisible()
		lw.pack();

		mainFrame.centerWindow(lw);

		// auto-login:
		// lw.setVisible(true);
		mainFrame.registerControllers(); // this was called by login click ok in
											// ControllerRegister method below
											// before

	}
}

/*
 * Event handler for login window. After the user logs in (after login window
 * closes), the controllers that handle events on the menu items are created.
 * The controllers cannot be created before the user logs in because the
 * database connection is not valid at that time. The models that are created by
 * the controllers require a valid database connection.
 */
class ControllerRegister extends WindowAdapter {
	private MainView mvb;

	public ControllerRegister(MainView mvb) {
		this.mvb = mvb;
	}

	public void windowClosed(WindowEvent e) {
		mvb.registerControllers();
	}
}
